<template>

	<view class="contain">
		<view class="content">
			<!-- 注意，如果需要兼容微信小程序，最好通过setRules方法设置rules规则 -->
			<u--form labelPosition="left" :model="userInfo" :rules="rules" ref="form1" labelWidth="80">
				<!-- 请假人 -->
				<u-form-item label="家长姓名:" prop="userName" borderBottom ref="item1" required><u--input  v-model="userInfo.userName"
						border="none"></u--input></u-form-item>
				<!-- 班级 -->
				<u-form-item label="亲属关系:" prop="relationship" borderBottom @click="openAction('亲属关系')" ref="item1" required>
					<u--input v-model="userInfo.relationship" disabled disabledColor="#ffffff" placeholder="请选择亲属关系"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<!-- 联系方式 -->
				<u-form-item label="家长手机:" prop="userMobile"   borderBottom ref="item1" required><u--input  v-model="userInfo.userMobile"
						border="none"></u--input></u-form-item>
				<!-- 报修类型 -->
				<u-form-item label="证件类型:" prop="userIdCardType" borderBottom @click="openAction('证件类型')" ref="item1">
					<u--input v-model="userInfo.userIdCardType" disabled disabledColor="#ffffff" placeholder="请选择证件类型"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				
				<u-form-item label="证件号码:" prop="userIdCard" borderBottom ref="item1" required><u--input v-model="userInfo.userIdCard"
						border="none"></u--input></u-form-item>
				
				<u-form-item label="民族:" prop="userNation" borderBottom @click="openAction('民族')" ref="item1">
					<u--input v-model="userInfo.userNation" disabled disabledColor="#ffffff" placeholder="请选择民族"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				
				<u-form-item label="教育程度:" prop="userEducation" borderBottom @click="openAction('教育程度')" ref="item1">
					<u--input v-model="userInfo.userEducation" disabled disabledColor="#ffffff" placeholder="请选择教育程度"
						border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				
				<u-form-item label="家长职业:" v-model="userInfo.userOccupation" borderBottom ref="item1"><u--input   v-model="userInfo.userOccupation"
						border="none"></u--input></u-form-item>
				
				<u-form-item label="电子邮箱:" v-model="userInfo.userEmail" borderBottom ref="item1"><u--input   v-model="userInfo.userEmail"
						border="none"></u--input></u-form-item>
			</u--form>
			<button @click="submit" class="btn">提交</button>
			<u-datetime-picker :minDate='minDate' :show="showDate" @cancel="showDate = false" @confirm="selectDate" v-model="dateTime"
				mode="datetime"></u-datetime-picker>

			<u-action-sheet :round='10' :show="showSex" :actions="actions" :title="actionTitle" @close="showSex = false"
				@select="Select"></u-action-sheet>

		</view>
		<!-- <u-tabbar :value="tabbarIndex" @change="click" :fixed="true" :border="true" activeColor='#1cb8a7'>
			<u-tabbar-item text="申请" icon="edit-pen-fill" @click='clickTabbar'></u-tabbar-item>
			<u-tabbar-item text="列表" icon="file-text-fill" @click='clickTabbar'></u-tabbar-item>

		</u-tabbar> -->
	</view>
</template>

<script>
	 import {save,update} from '@/api/parents.js';
	export default {
		options: { styleIsolation: 'shared' },//解决/deep/不生效**
		data() {
			return {
				showSex: false,
				minDate:Date.parse(new Date()),
				userInfo: {
					userName:'',
					userMobile:'',
					relationship:'',
					userIdCardType:'',
					firstContacts:'0'
				},
				dateTime: Number(new Date()),
				actions: [],
				rules: {
					'userName': {
						type: 'string',
						required: true,
						message: '请输入家长姓名',
						trigger: ['blur', 'change']
					},
					'relationship': {
						type: 'string',
						required: true,
						message: '请选择亲属关系',
						trigger: ['blur', 'change']
					},
					'userMobile': {
						type: 'string',
						required: true,
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							return uni.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						// 触发器可以同时用blur和change
								
					},
					 'userIdCard': {
						type: 'string',
						required: true,
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							// 上面有说，返回true表示校验通过，返回false表示不通过
							// uni.$u.test.mobile()就是返回true或者false的
							return uni.$u.test.idCard(value);
						},
						message: '身份证号码不正确',
						// 触发器可以同时用blur和change
								
					},
				},
				radio: '',
				switchVal: false,
				actionTitle: '请选择报修类型',
				showDate: false, //日期选择
				fileList1: [], //上传图片
				tabbarIndex: 0,
				dateType: 'start',
				checkPerson: [],
				leaveType: [],
				radios: [],
				activeIndex: '', //病症
				showMalady: false,
				rangetwo:[],
				userIdCardTypelist:[],
				userNation:[],
				userEducationlist:[],
				newUserInfo:{}
			};
		},
		watch: {
			radios: {
				handler(newVal, oldVal) {
					newVal.forEach(it => {
						if (it.checked) {
							this.userInfo.content = this.userInfo.content + it.name
						} else {
							this.userInfo.content = this.userInfo.content.replace(it.name, '')
						}
					})
				},
				deep: true
				
			},

		},
		onLoad(item) {
			// 获取请假类型
			// "typeId": "string",
			// "typeName": "string",
			// 获取审批人
			// 获取字典项
			
			let list2 = this.$util.getdictionary('亲属关系');
			list2.forEach((childItem, i) => {
				this.rangetwo.push({id:childItem.value ,name:childItem.name})
			})
			
			
			
			let list = this.$util.getdictionary('身份证件类型');
			list.forEach((childItem, i) => {
				this.userIdCardTypelist.push({id:childItem.value ,name:childItem.name})
			})
			
			if(this.userIdCardTypelist.length>0){
				this.userInfo.userIdCardType = this.userIdCardTypelist[0].name;
				this.userInfo.userIdCardTypeId = this.userIdCardTypelist[0].id;
			}
			
			let list3 = this.$util.getdictionary('民族');
			list3.forEach((childItem, i) => {
				this.userNation.push({id:childItem.value ,name:childItem.name})
			})
			
			let list4 = this.$util.getdictionary('教育程度');
			list4.forEach((childItem, i) => {
				this.userEducationlist.push({id:childItem.value ,name:childItem.name})
			})
			
			
			
			if(item.editlist){
			this.userInfo = JSON.parse(item.editlist);
			this.newUserInfo = JSON.parse(item.editlist);
			uni.setNavigationBarTitle({
				title:'编辑信息'
			})
			this.rangetwo.forEach(op=>{
				if(op.id == this.userInfo.relationship){
					this.userInfo.relationship = op.name;
					this.userInfo.relationshipId = op.id;
				}
			})
			this.userIdCardTypelist.forEach(op=>{
				if(op.id == this.userInfo.userIdCardType){
					this.userInfo.userIdCardType = op.name;
					this.userInfo.userIdCardTypeId = op.id;
				}
			})
			
			this.userNation.forEach(op=>{
				if(op.id == this.userInfo.userNation){
					this.userInfo.userNation = op.name;
					this.userInfo.userNationId = op.id;
				}
			})
			
			this.userEducationlist.forEach(op=>{
				if(op.id == this.userInfo.userEducation){
					this.userInfo.userEducation = op.name;
					this.userInfo.userEducationId = op.id;
				}
			})
			
			}
			// this.getToken()
		},
		
		onUnload() {
			//#ifdef MP-WEIXIN
			uni.reLaunch({
				url: '/pages/tabbar/index/index'
			})
			//#endif
		},
		methods: {
			
			// 获取字典项
			getDiction() {
				let radio = this.$util.getdictionary('病症');
				console.log('sssssssssssssss字典项', radio)
				if(radio){
				radio.forEach((item, i) => {
					this.radios.push({
						name: item.name,
						value: item.value,
						checked: false
					});
				})	
				}
				
				
			},
			radioClick(it, i) {
				this.activeIndex = i;
				this.radios.map((itm, index) => {
					if (i == index) {
						if (itm.checked) {
							itm.checked = false
						} else {
							itm.checked = true
						}

					} else {
						itm.checked = false
					}
					return itm
				})

				console.log('this.radios', this.radios)
				// this.getData(this.params)
			},
			// 获取审批人
			async getPageStaff(pa) {
				const {
					data
				} = await pageStaff(pa)
				console.log('打印返回', data)
				if (data.code == 0) {
					data.data.list.forEach(it => {
						this.checkPerson.push({
							name: it.userName,
							id: it.userId
						})
					})

				}
			},
			// 获取请假类型
			async getleaveType() {
				const {
					data
				} = await leaveType()

				if (data.code == 0) {
					data.data.list.forEach(it => {
						this.leaveType.push({
							name: it.typeName,
							id: it.typeId
						})
					})

				}

			},
			openDate(type) {
				this.showDate = true;
				this.dateType = type
			},
			clickTabbar(e) {
				this.tabbarIndex = e
				console.log('eeeee', e)
				if (this.tabbarIndex == 0) {
					uni.redirectTo({
						url: '/pages/subPack/leave/apply'
					})
				} else if (this.tabbarIndex == 1) {
					uni.redirectTo({
						url: '/pages/subPack/leave/list'
					})
				}
			},
			click() {

			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1);
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				console.log('选择图片', event.file);
				let fileListLen = this[`fileList${event.name}`].length;
				lists.map(item => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					});
				});
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url);
					let item = this[`fileList${event.name}`][fileListLen];
					this[`fileList${event.name}`].splice(
						fileListLen,
						1,
						Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						})
					);
					fileListLen++;
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$config.URL + 'api/app/sysFile/v1/save', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						success: res => {
							resolve(JSON.parse(res.data).url);

						}
					});
				});
			},
			selectDate(d) {
				if (this.dateType == 'start') {
					this.userInfo.startTime = this.format(d.value);
				} else {
					
					this.userInfo.endTime = this.format(d.value);
				}
				if (this.userInfo.startTime && this.userInfo.endTime) {
					
					this.userInfo.duration = this.getDays(this.userInfo.startTime.substring(0, 10), this
						.userInfo.endTime.substring(0, 10))
					if(this.userInfo.duration>0||this.userInfo.duration==0){
						this.userInfo.durationDay=this.userInfo.duration+'天'
					}else{
						this.$api.showTip('结束时间不能小于开始时间')
					}
						
				}
				this.showDate = false;
			},
			format(shijianchuo) {
				//shijianchuo是整数，否则要parseInt转换
				var time = new Date(shijianchuo);
				var y = time.getFullYear();
				var m = time.getMonth() + 1;
				var d = time.getDate();
				var h = time.getHours();
				var mm = time.getMinutes();
				var s = time.getSeconds();
				return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this
					.add0(s);
			},
			add0(m) {
				return m < 10 ? '0' + m : m;
			},
			// 提交
			submit() {
				// 获取提交信息
				this.$refs.form1.validate().then(res => {
					this.newUserInfo.relationship = this.userInfo.relationshipId;
					this.newUserInfo.userIdCardType = this.userInfo.userIdCardTypeId;
					this.newUserInfo.userNation = this.userInfo.userNationId;
					this.newUserInfo.userEducation = this.userInfo.userEducationId;
					this.newUserInfo.userName = this.userInfo.userName;
					this.newUserInfo.userIdCard = this.userInfo.userIdCard;
					this.newUserInfo.userMobile = this.userInfo.userMobile;
					this.newUserInfo.userOccupation = this.userInfo.userOccupation;
					this.newUserInfo.userEmail = this.userInfo.userEmail;
					this.newUserInfo.firstContacts = this.userInfo.firstContacts;
					// this.userInfo.relationship = this.userInfo.relationshipId;
					// this.userInfo.userIdCardType = this.userInfo.userIdCardTypeId;
					// this.userInfo.userNation = this.userInfo.userNationId;
					// this.userInfo.userEducation = this.userInfo.userEducationId;
					
					if(this.userInfo.userId){
						// this.newUserInfo.studentId = 
						update(this.newUserInfo).then(
							res => {
								uni.hideLoading()
								if (res.data.code == "0") {
									this.$api.showTip("添加成功", () => {
										// self.notification(res.data.data.applyId)
										uni.redirectTo({
											url: "list"
										})
									});
								} else {
									this.$api.showTip(res.data.msg);
								}
							},
							err => {
								uni.hideLoading();
								this.$api.showTip('服务器错误');
							}
						);
					}else{
						// this.userInfo.studentId = this.$util.getChild().userId;
						// newUserInfo = this.userInfo;
						this.newUserInfo.studentId = this.$util.getChild().userId;
						
						save(this.newUserInfo).then(
							res => {
								uni.hideLoading()
								if (res.data.code == "0") {
									this.$api.showTip("添加成功", () => {
										// self.notification(res.data.data.applyId)
										uni.redirectTo({
											url: "list"
										})
									});
								} else {
									this.$api.showTip(res.data.msg);
								}
							},
							err => {
								uni.hideLoading();
								this.$api.showTip('服务器错误');
							}
						);
					}
				
				}).catch(errors => {
					
				})
			},
			// getToken() {
			// 	let self = this
			// 	wx.requestSubscribeMessage({
			// 		tmplIds: ['4y98Suoq_O67JCFh0B9VSDpQeRn5SSWgP791QAoLSEY'], //此处的id替换你要发送订阅的模板id,可在小程序后台新建模板中获取
			// 		success(res) {
			// 			wx.request({
			// 				url: `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${uni.getStorageSync('appid')}&secret=${uni.getStorageSync('secret')}`,
			// 				data: {},
			// 				success: function(res) {
			// 					self.mytoken = res.data.access_token
								
			// 				}
			// 			})
			// 		},
			// 		fail: function(res) {
			
			// 		}
			// 	})
			// },
			notification(id) {
				console.log('获取通知id',id)
				let self = this
				//下方的thing1，thing2和其他，对应的是你选取模板的模板详情中的字段名称(可在小程序后台模板查看对应的字段，要和上面的字段一样)，需要更改成你自己的
				const pushmsg = {
					"touser": 'og0wa4wzukRgZ9b8Awyh2Wf3el0U',
					"template_id": "4y98Suoq_O67JCFh0B9VSDpQeRn5SSWgP791QAoLSEY",
					"data": {
						"name2": {
							"value": "小花"
						},
						"name1": {
							"value": "小一班"
						},
						"phrase3": {
							"value": "事假"
						},
						"date4": {
							"value": this.userInfo.startTime
						},
						"time11": {
							"value": this.userInfo.endTime
						}
					},
					'page':'/pages/subPack/leave/detail?id='+id
				}
				wx.request({
					url: 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=' + self.mytoken,
					data: JSON.stringify(pushmsg),
					method: 'POST',
					success: function(res) {
						console.log(res)
					}
				})
			},
			// 大计算天数
			getDays(startDate, endDate) {
				var date1Str = startDate.split("-"); //将日期字符串分隔为数组，数组元素分别为年、月、日      
				//根据年、月、日的值创建Date对象
				var date1Obj = new Date(date1Str[0], (date1Str[1] - 1), date1Str[2]);
				var date2Str = endDate.split("-");
				var date2Obj = new Date(date2Str[0], (date2Str[1] - 1), date2Str[2]);
				var t1 = date1Obj.getTime(); //返回从1970-1-1开始计算到Date对象中的时间之间的毫秒数
				var t2 = date2Obj.getTime(); //返回从1970-1-1开始计算到Date对象中的时间之间的毫秒数
				var datetime = 1000 * 60 * 60 * 24; //一天时间的毫秒值 
				var minusDays = Math.floor(((t2 - t1) / datetime)); //计算出两个日期天数差 
				var days = Math.abs(minusDays); //如果结果为负数，取绝对值
				minusDays = minusDays + 1;
				return minusDays;
			},
			openAction(text) {
				if (text == '亲属关系') {
					this.actionTitle = '请选择亲属关系';
					this.actions = this.rangetwo;
				} else if (text == '证件类型') {
					this.actionTitle = '请选择证件类型';
					this.actions = this.userIdCardTypelist
				}else if(text == '民族'){
					this.actionTitle = '请选择民族';
					this.actions = this.userNation
				}else if(text == '教育程度'){
					this.actionTitle = '请选择教育程度';
					this.actions = this.userEducationlist
				}

				this.showSex = true;
			},
			// 选择
			Select(e) {
				console.log('选择了那个', e)
				if (this.actionTitle == '请选择亲属关系') {
					console.log('选择了那个', e)
					this.userInfo.relationship = e.name;
					this.userInfo.relationshipId=e.id;
				} else if (this.actionTitle == '请选择证件类型') {
					this.userInfo.userIdCardType = e.name;
					this.userInfo.userIdCardTypeId = e.id;
				}else if (this.actionTitle == '请选择民族') {
					this.userInfo.userNation = e.name;
					this.userInfo.userNationId = e.id;
				}else if (this.actionTitle == '请选择教育程度') {
					this.userInfo.userEducation = e.name;
					this.userInfo.userEducationId = e.id;
				}

				// this.$refs.form1.validateField('userInfo.sex')
			}
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules);
		}
	};
</script>
<style lang="less" scoped>
	.contain {
		width: 100%;
		height: 100%;
		background-color: #fff;
	}
	/deep/.u-icon__icon{
		font-size: 50rpx!important
	}
	
	.u-page__tag-item {
		display: inline-block;
		margin-right: 30rpx;
		margin-bottom: 10rpx;
		margin-top: 30rpx;
	}

	.content {
		padding: 30rpx 50rpx;
	}


	/deep/.uni-input-input {
		text-align: right;
	}

	/deep/.uni-input-placeholder {
		text-align: right;
	}

	/deep/.uni-textarea-placeholder {
		text-align: right;
	}

	/deep/.u-upload {
		align-items: end;
	}

	

	// 底部
	/deep/.u-tabbar--fixed {
		border-top: 1px solid #dadbde;
	}

	/deep/.u-icon__icon {
		// font-size: 48rpx!important
	}

	/deep/.u-tabbar-item__text {
		font-size: 26rpx
	}
	/deep/.u-form-item__body__right__content__slot{
		justify-content: end;
	}
	/deep/.u-textarea{
		text-align: end;
	}
	/deep/ .u-popup__content{
		padding-bottom: 20px!important;
	}
	
	/deep/.u-action-sheet {
		height: 400px;
		overflow: scroll;
	}
</style>